import React, { useEffect, lazy, useState } from "react";
import { useSearchParams, Outlet } from "react-router-dom";
import useUserStore, { useUserActions } from "../store/userStore";
import { CircleLoading } from '@/components/loading';
import { ErrorBoundary } from 'react-error-boundary';
const PageError = lazy(() => import('@/pages/error/PageError'));

const WithRouter = () => {
  let [isPending, setIsPending] = useState(true)
  let [searchParams, setSearchParams] = useSearchParams();
  const { getEnvConfig, getUserInfo, setUserToken, setLoginHint } = useUserActions()
  const userStore = useUserStore()

  useEffect(() => {
    // 微前端环境（作为子应用）
    if (window.__MFE_ENV__) {
      const { token } = window.MFE?.getGlobalData()
      setUserToken(token)
    } else if (searchParams.get("token") || localStorage.getItem("access_token")) {
      setUserToken(searchParams.get("token") || localStorage.getItem("access_token"))
    }

    initUser()

    // setTimeout(() => {
    //   setUserToken(122222)
    // }, 10000)
  }, [])

  const initUser = async () => {
    const [_, userInfoRes] = await Promise.all([getConfig(), getUserInfo()])
    // if (userInfoRes && [401, 500].includes(userInfoRes.code)) {
    //   setLoginHint({
    //     title: '登录提示',
    //     content: userInfoRes.message,
    //     show: true
    //   })
    // }
    setIsPending(false)
  }

  const getConfig = () => {
    if (userStore.constantObjSSO && userStore.constantObjSSO.SSO_HOST) {
      return Promise.resolve({})
    }
    return getEnvConfig()
  }

  if (isPending) {
    return <CircleLoading />
  }
  return <ErrorBoundary FallbackComponent={PageError}><Outlet /></ErrorBoundary>;
};

export default WithRouter;
